package lion.framework.core.web.request;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import lion.framework.core.web.exception.WebException;
import lion.framework.core.web.path.PathNode;
import lion.framework.core.web.path.PathNodeExecutor;
import lion.framework.core.web.path.PathNodeMapping;
import lion.framework.core.web.request.multi.MultiRequestWrapper;

/**
 * 请求处理类 在执行
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年3月18日
 */
public class RequestHandler {

	private int filterIndex = 0;
	private String path;
	private FilterChain chain;
	private boolean handled = false;

	public RequestHandler(String path, FilterChain chain) {

		this.path = path;
		this.chain = chain;
	}

	public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (handled) { throw new WebException("request handled already"); }

		RequestInterceptor filter = RequestInterceptorManager.getInterceptor(filterIndex);
		if (filter != null) {
			filterIndex++;
			filter.intercept(request, response, this);
			return;
		}
		handled = true;

		PathNode node = null;
		if (("/".equals(path) || StringUtils.isBlank(path)) && !PathNodeMapping.getRootPathNode().getViewConfig().isEmpty()) {
			node = PathNodeMapping.getRootPathNode();
		} else {
			node = PathNodeMapping.find(path);
		}
		if (node != null) {
			if (ServletFileUpload.isMultipartContent(request)) {
				request = new MultiRequestWrapper(request);
			}
			try {
				new PathNodeExecutor(node).execute(request, response);
			} finally {
				if (ServletFileUpload.isMultipartContent(request)) {
					((MultiRequestWrapper) request).cleanUp();
				}
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	public String getPath() {

		return this.path;
	}

}
